package com.lm.controller;

import com.lm.utils.ConfigUtil;
import com.meirengu.common.StatusCode;
import com.meirengu.controller.BaseController;
import com.meirengu.model.Result;
import com.meirengu.utils.OSSFileUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.IOException;
import java.util.Map;

@Controller
@RequestMapping("upload")
public class UploadController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(UploadController.class);

    @ResponseBody
    @RequestMapping("portrait")
    private Result portrait(MultipartHttpServletRequest request) {
        //文件夹名
        String interrogation = ConfigUtil.getConfig("user.portrait");
        return this.upload(request, interrogation);
    }

    public Result upload(MultipartHttpServletRequest request, String folderName) {

        //file组件的name
        String file = "file";
        String endpoint = ConfigUtil.getConfig("endpoint");
        String accessKeyId = ConfigUtil.getConfig("accessKeyId");
        String accessKeySecret = ConfigUtil.getConfig("accessKeySecret");
        String bucketName = ConfigUtil.getConfig("bucketName");
        String callbackUrl = ConfigUtil.getConfig("callbackUrl");
        String fileSize = ConfigUtil.getConfig("fileSize");//文件大小限制
        logger.info("uc upload init :{}", endpoint);
        try {
            if (request.getFile("file").getSize() > Integer.parseInt(fileSize)) {
                logger.info("上传文件大小:{}，限制大小:{}", request.getFile("file").getSize(), fileSize);
                return super.setResult(StatusCode.UPLOAD_SIZE_ERROR, null, StatusCode.codeMsgMap.get(StatusCode.UPLOAD_SIZE_ERROR));
            }

            OSSFileUtils fileUtils = new OSSFileUtils(endpoint, accessKeyId, accessKeySecret, bucketName, callbackUrl);
            Map<String, String> map = fileUtils.upload(request, file, folderName);
            String pictureName = "";
            if (map != null) {
                pictureName = map.get("pictureName");
            }
            return super.setResult(StatusCode.OK, folderName + "/" + pictureName, StatusCode.codeMsgMap.get(StatusCode.OK));
        } catch (IOException e) {
            String params = String.format("参数:folderName:%s", folderName);
            logger.error("UploadController portrait throws Exceprion :{} happens. params:{}.", ExceptionUtils.getFullStackTrace(e), params);
            return super.setResult(StatusCode.UNKNOWN_EXCEPTION, null, StatusCode.codeMsgMap.get(StatusCode.UNKNOWN_EXCEPTION));
        }
    }
}
